<?php
/**
 * Created by 匠言.
 * User: yyd
 * Date: 2018/5/10
 * Time: 13:47
 */
namespace org;
use think\Controller;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Qiniu\Config;
use Qiniu\Processing\PersistentFop;
use Qiniu\Storage\ResumeUploader;
use think\Db;
use think\Request;
use function Qiniu\base64_urlSafeEncode;

class Qiniu extends Controller
{
    public $callbackUrl = "https://xxx.com";
    private $config = [];
    //引入文件
    public function _initialize(){
        require_once '../extend/qiniu/autoload.php';
        $storage_config=Db::name('storage')->field('qiniu')
            ->where('acid',1)
            ->find();
        $this->config = json_decode($storage_config['qiniu'], true);
    }

    /**
     * auth 鉴权
     * @return Auth
     */
    public function auth(){
        // 用于签名的公钥和私钥
        $accessKey = $this->config['accessKey']; //config('qiniu.accessKey');
        $secretKey = $this->config['secretKey']; //config('qiniu.secretKey');
        // 初始化签权对象
        $auth = new Auth($accessKey, $secretKey);
        return $auth;
    }

    /**
     * uploadFile 上传文件(图片&音频)
     * @param $filePath 文件地址
     * @param $key 组装的文件名
     * @param $domain 前缀
     * @return string 返回上传地址
     * @throws \Exception
     */
    public function uploadFile($filePath,$key){
        set_time_limit(0);
        $auth = $this->auth();
        //储存空间
        $bucket = $this->config['bucket']; //config('qiniu.bucket');

        $policy = array(
            'callbackBody' => 'filename=$(fname)&filesize=$(fsize)'
        );
        // 生成上传Token
        $uptoken = $auth->uploadToken($bucket, null, 3600, $policy);
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($uptoken, $key, $filePath);
        if ($err !== null) {
            return $ret['key'];
        } else {
            return $ret['key'];
        }
    }

    /**
     * 上传视频&转码
     * @param $filePath 文件地址
     * @param $key 组装的文件名
     * @param $domain 前缀
     * @return string 返回上传地址
     * @throws \Exception
     */
    public function uploadVideo($filePath,$key){
        $auth = $this->auth();
        //储存空间
        $bucket = $this->config['bucket']; //config('qiniu.bucket');
        $policy = array(
//            'callbackBody' => 'filename=$(fname)&filesize=$(fsize)'
            'callbackBody' => '{"fname":"$(fname)", "fkey":"$(key)", "desc":"$(x:desc)"}'
        );
        // 生成上传Token
        $uptoken = $auth->uploadToken($bucket, null, 3600, $policy);
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($uptoken, $key, $filePath);
//        if ($err !== null) {
//            return $ret['key'];
//        } else {
//            return $ret['key'];
//        }
        return $ret;
        dd($ret);
        die();
        $config = new Config();
        $pipeline = config('pipeline');
        $force = false;
        $k =  $ret['key'];
        $pfop = new PersistentFop($auth, $config);
        $name = md5(time().uuid()).".mp4";
        $fops = "avthumb/mp4/vcodec/libx264|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .':'. $name);
        list($id, $err) = $pfop->execute($bucket, $k, $fops, $pipeline, '', $force);
        //查询转码的进度和状态
        list($sta, $err) = $pfop->status($id);
//        echo "\n====> pfop avthumb status: \n";
        if ($sta != null) {
            return $name;
        } else {
            return $name;
        }
    }

    /**
     * deleteFile 删除图片
     * @param $key 图片名称
     * @param $bucket
     * @return mixed
     */
    public function delFile($key,$bucket){
        $auth = $this->auth();
        $config = new Config();
        $bucketManager = new BucketManager($auth, $config);
        $err = $bucketManager->delete($bucket, $key);
        return $err;
    }

    /**
     * delMoreFile 批量删除
     * @param $keys 图片数组 //每次最多不能超过1000个
     * @param $bucket 空间名
     * @return mixed
     */
    public function delMoreFile($keys,$bucket){
        $auth = $this->auth();
        $config = new Config();
        $bucketManager = new BucketManager($auth, $config);
        $ops = $bucketManager->buildBatchDelete($bucket, $keys);
        list($ret, $err) = $bucketManager->batch($ops);
        if ($err) {
            return $err;
        } else {
            return $ret;
        }
    }

    public function upTokenByM3u8($fileName = null){
        $auth = $this->auth();
        $bucket = $this->config['bucket']; //config('qiniu.bucket');
        $fileName_arr = explode('.',$fileName);
        $file_type = end($fileName_arr);
        $baseFileName = base64_urlSafeEncode(str_replace($file_type,  'm3u8', $fileName));
        $persistentOps = $fileName ? "avthumb/m3u8|saveas/{$baseFileName}" : "avthumb/m3u8";
        $persistentPipeline = $this->config['pipeline']; //config('qiniu.pipeline');
        $callbackBody =  '{"fname":"$(fname)", "fkey":"$(key)", "desc":"$(x:desc)"}';
        $persistentNotifyUrl = "https://xx.com";
        $policy = compact("callbackBody","persistentPipeline","persistentOps","persistentNotifyUrl");
        return $auth->uploadToken($bucket,null, 3600,$policy);
    }

    public function verifyCallbackBody(){
        $auth = $this->auth();
        $callbackBody = file_get_contents('php://input');
        //回调的contentType
        $contentType = 'application/x-www-form-urlencoded';
        //回调的签名信息，可以验证该回调是否来自存储服务
        $authorization = $_SERVER['HTTP_AUTHORIZATION'];
        $isQiniuCallback = $auth->verifyCallback($contentType,$authorization,$this->callbackUrl,$callbackBody);
        if ($isQiniuCallback) {
            $resp = array('ret' => 'success', 'data' => $callbackBody);
        } else {
            $resp = array('ret' => 'failed');
        }
        return json_encode($resp);
    }

    /**
     * 转码
     * $key 已上传的文件名
     * $options 转码参数
     * return $id 资源id
    */
    public function PersistentFop($key, $options){
        $auth = $this->auth();
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $bucket = $this->config['bucket'];
        $pipeline = $this->config['pipeline_fops'];//转码专用通道
       /* $options = [
            'totype' => 'm3u8',
            'use_watermark' => true,
            'watermark_type' => 'wmText', // wmText | wmImage | wmVideo
            'watermark_addr' => 'url', // 水印地址
            'watermark_location' => 'url', // 水印位置
        ];*/
        $fops = 'avthumb/' . $options['totype'];
        if(!empty($options['use_watermark']) && $options['use_watermark']) {
            if($options['watermark_type'] == 'wmText') {
                $options['watermark_addr'] = $options['watermark_text'];
            } elseif($options['watermark_type'] == 'wmImage') {
                $options['watermark_addr'] = $options['watermark_image_addr'];
            }
            $fops .= "/{$options['watermark_type']}/" . base64_urlSafeEncode($options['watermark_addr']);
            if($options['watermark_type'] == 'wmImage') {
                $fops .= "/wmGravity/{$options['watermark_location']}";
            }
        }
        $arr = explode('.', $key);
        $newname = $arr[0].'_'.$options['totype']. '.' . $options['totype'];
        $fops .= '|saveas/' . base64_urlSafeEncode($bucket . ":" . $newname);
//        $fops .= '|saveas/' . base64_urlSafeEncode($bucket);
        $notifyUrl = '';
        $force = false;
        //$fops = "avthumb/mp4/s/640x360/vb/1.4m|saveas/" . base64_urlSafeEncode($bucket . ":" . $key);

        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);
        if ($err != null) {
            return ['code' => 1, 'msg' => $err];
        } else {
            return ['code' => 0, 'msg' => $id];
        }
    }

    /**
     * 查询转码进度
     * $key 已上传的文件名
     */
    public function queryPersistentFopStatus($id){
        $auth = $this->auth();
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        list($ret, $err) = $pfop->status($id);
        if ($err != null) {
            return ['code' => 1, 'msg' => $err];
        } else {
            return ['code' => 0, 'msg' => $ret];
        }
    }
}